package com.wsm.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.wsm.common.enums.BaseEnum;
import com.wsm.common.utils.ShiroUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * <p> MyBatisPlus自定义字段自动填充处理类 - 实体类中使用 @TableField注解 </p>
 *
 * @description: 注意前端传值时要为null
 * @author: zhengqing
 * @date: 2019/8/18 0018 1:46
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static String gmtCreate = "gmtCreate";
    private static String gmtModified = "gmtModified";

    private static String gmtCreateId = "gmtCreateId";
    private static String gmtModifiedId = "gmtModifiedId";

    private static String useFlag = "useFlag";
    private static String delFlag = "delFlag";

    /**
     * 创建时间
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasSetter(gmtCreate)) {
            setFieldValByName(gmtCreate, new Date(), metaObject);
        }
        if (metaObject.hasSetter(gmtCreateId)) {
            setFieldValByName(gmtCreateId, ShiroUtils.getUserId(), metaObject);
        }
        if (metaObject.hasSetter(useFlag)) {
            setFieldValByName(useFlag, BaseEnum.USE_FLAG.YES.getCode(), metaObject);
        }
        if (metaObject.hasSetter(delFlag)) {
            setFieldValByName(delFlag, BaseEnum.DEL_FLAF.Not_del.getCode(), metaObject);
        }
    }

    /**
     * 最后一次更新时间
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasSetter(gmtModified)) {
            setFieldValByName(gmtModified, new Date(), metaObject);
        }
        if (metaObject.hasSetter(gmtModifiedId)) {
            setFieldValByName(gmtModifiedId, ShiroUtils.getUserId(), metaObject);
        }
    }

}
